<template>
  <div>
    <h1>订单列表</h1>
    <el-form :inline="true" :model="listFrom" class="demo-form-inline">
      <el-form-item label="请输入关键字/商品名称/id">
        <el-input
          v-model="listFrom.keyWord"
          placeholder="请输入关键字/商品名称/id"
          clearable
        />
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select
          v-model="listFrom.prodStatus"
          placeholder="请选择订单状态"
          clearable
          style="width: 160px"
        >
          <el-option label="未支付" value="0" />
          <el-option label="已支付" value="1" />
          <el-option label="待发货" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型">
        <el-select
          v-model="listFrom.typeId"
          placeholder="请选择订单类型"
          clearable
          style="width: 160px"
        >
          <el-option
            v-for="item in typeList"
            :label="item.dictName"
            :value="item.dictValue"
            :key="item.dictId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="list()">查询</el-button>
        <el-button type="danger" @click="OnDelete()">批量删除</el-button>
        <el-button type="info" @click="OnGetExel()">导出</el-button>
        <el-button type="drang" @click="OnAddOrder()">添加订单</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="orderId" label="ID" />
      <el-table-column prop="orderNo" label="订单编号" />
      <el-table-column prop="prodInfo" label="商品信息" />
      <el-table-column prop="orderAmount" label="订单金额" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="createBy" label="消费者" />
      <el-table-column label="商品图片">
        <template #default="scope">
          <el-image
            v-for="item in scope.row.imageList"
            :src="item"
            style="width: 50px; height: 50px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.orderStatus == 0"
            >未支付</el-tag
          >
          <el-tag type="success" v-if="scope.row.orderStatus == 1"
            >已支付</el-tag
          >
          <el-tag type="info" v-if="scope.row.orderStatus == 2">待发货</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作"> </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <div class="demonstration"></div>
      <el-pagination
        v-model:current-page="listFrom.pageNum"
        v-model:page-size="listFrom.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加订单页面" width="900">
        <el-form :model="form" :rules="rules" ref="ruleFormRef">
          <el-form-item label="选择商品" :label-width="formLabelWidth">
            <el-select
              v-model="form.infoId"
              placeholder="请选择商品"
              clearable
              style="width: 160px"
            >
              <el-option
                v-for="item in prodinfoList"
                :label="item.prodName"
                :value="item.infoId"
                :key="item.infoId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="购买数量" :label-width="formLabelWidth">
            <el-input v-model="form.buyNum" autocomplete="off" />
          </el-form-item>
          <div>
            <el-button type="danger" @click="OnAddProdInfoList()"
              >添加</el-button
            >
          </div>
          <el-form-item
            label="选择的商品"
            :label-width="formLabelWidth"
            prop="prodinfoData"
          >
            <el-table :data="form.prodinfoData" border style="width: 100%">
              <el-table-column prop="prodId" label="商品ID" width="180" />
              <el-table-column prop="prodName" label="商品名称" width="180" />
              <el-table-column prop="prodPrice" label="商品价格" />
              <el-table-column prop="buyNum" label="购买数量" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="small"
                    @click="OnIndexDelete(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <div>商品总价:{{ totalAmount }} 元</div>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import {
  getOrderList,
  getDictList,
  deleteOrderBatch,
  getProdInfoList,
  addProdInfoList,
} from "../api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
const ruleFormRef = ref<FormInstance>();
const tableData = ref([]);
const typeList = ref([]);
const prodinfoData = ref([]);
const prodinfoList = ref([]);
const totalAmount = ref(0);
//列表
const listFrom = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: "",
  typeId: null,
  prodStatus: null,
});
//添加订单
const form = ref({
  prodId: null,
  buyNum: 1,
  infoId: null,
  prodinfoData: [],
});
const total = ref(0);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
//列表
const list = () => {
  getOrderList(listFrom.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  listFrom.value.pageSize = val;
  list();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  listFrom.value.pageNum = val;
  list();
};
//批量删除
const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
const OnDelete = () => {
  let ids = [];
  if (multipleSelection.value.length <= 0) {
    ElMessage.error("请选择要删除的数据");
    return;
  }
  multipleSelection.value.forEach((item) => {
    ids.push(item.orderId);
  });
  ElMessageBox.confirm(
    "数据一旦删除就无法恢复，您确定要继续进行删除吗?",
    "删除警告框",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "error",
    }
  )
    .then(() => {
      deleteOrderBatch(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          list();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "用户已取消操作",
      });
    });
};
//导出
const OnGetExel = () => {
  let url = "http://localhost:9022/prod/order/getExel";
  window.open(url);
};
//添加订单
const OnAddOrder = () => {
  dialogFormVisible.value = true;
  form.value = {
    infoId: null,
    buyNum: 1,
    prodinfoData: [],
  };
  totalAmount.value = 0.0;
};
//追加
const OnAddProdInfoList = () => {
  prodinfoList.value.forEach((item) => {
    if (item.infoId == form.value.infoId) {
      item.buyNum = form.value.buyNum;
      form.value.prodinfoData.push(item);
    }
  });
  totalAmount.value = 0.0;
  form.value.prodinfoData.forEach((item) => {
    totalAmount.value += item.prodPrice * item.buyNum;
  });
};
//删除
const OnIndexDelete = (row: any) => {
  form.value.prodinfoData.forEach((item, index) => {
    if (item.infoId == row.infoId) {
      form.value.prodinfoData.splice(index, 1);
    }
  });
  totalAmount.value = 0.0;
  form.value.prodinfoData.forEach((item) => {
    totalAmount.value += item.prodPrice * item.buyNum;
  });
};
//添加订单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      addProdInfoList(form.value.prodinfoData).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          list();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//校验
const rules = reactive<FormRules>({
  prodinfoData: [{ required: true, message: "请追加商品", trigger: "blur" }],
});
onMounted(() => {
  list();
  //从字典表中获取订单类型
  getDictList(4).then((res) => {
    if (res.data.code == 200) {
      typeList.value = res.data.data;
    }
  });
  getProdInfoList().then((res) => {
    if (res.data.code == 200) {
      prodinfoList.value = res.data.data;
    }
  });
});
</script>
